//定制请求的实例

//导入axios  npm install axios
import axios from 'axios';

import { ElMessage } from 'element-plus'
//定义一个变量,记录公共的前缀  ,  baseURL
//const baseURL = 'http://localhost:8080/api';
const baseURL = '/api';
const instance = axios.create({ baseURL })

import {useTokenStore} from '@/stores/token.js'
//添加请求拦截器
instance.interceptors.request.use(
    (config)=>{
        //请求前的回调
        //添加token
        const tokenStore = useTokenStore();
        //判断有没有token
        if(tokenStore.token){
            config.headers.Authorization = tokenStore.token;
        }
        return config;
    },
    (err)=>{
        //请求错误的回调
        return Promise.reject(err)
    }
)

/* import {useRouter} from 'vue-router'
const router = useRouter(); */

import router from '@/router'
//添加响应拦截器
instance.interceptors.response.use(
    result => {
        //判断业务状态码
        if(result.data.code === 200){
            return result.data;
        }

        //操作失败
        ElMessage.error(result.data.message || '服务异常')
        //异步操作的状态转换为失败
        return Promise.reject(result.data)
    },
    err => {
        if (err.response) {
            const tokenStore = useTokenStore()
            
            switch (err.response.status) {
                case 401:
                    ElMessage.error(err.response.data.message || '请先登录')
                    // 清除 token
                    tokenStore.removeToken()
                    // 跳转到登录页
                    router.push({
                        path: '/login',
                        query: { redirect: router.currentRoute.value.fullPath }
                    })
                    break;
                case 403:
                    ElMessage.error(err.response.data.message || '无权限访问')
                    break;
                case 404:
                    ElMessage.error(err.response.data.message || '请求的资源不存在')
                    break;
                case 400:
                    ElMessage.error(err.response.data.message || '请求参数错误')
                    break;
                default:
                    ElMessage.error(err.response.data.message || '服务异常')
            }
        } else {
            ElMessage.error('网络连接异常')
        }
        return Promise.reject(err);
    }
)

export default instance;